<template>
  <div class="ry_scroll-container" :style="{ height: height }" ref="container">
    <div class="ry_scroll-content" ref="content">
      <slot></slot>
    </div>
  </div>
</template>
<script>
  export default {
    name: "RyScroll",
    props: {
      height: {
        type: String,
        default: () => ""
      }
    },
    methods:{
      scrollBy(width){
        this.$refs['container'].scrollBy({ behavior: 'smooth',left:width})
      }
    },
    mounted() {
      const { container } = this.$refs;
      const { content } = this.$refs;
      let isDown = false;
      let startX;
      let scrollLeft;
      // Mouse events for dragging
      container.addEventListener("mousedown", (e) => {
        isDown = true;
        container.classList.add("active");
        startX = e.pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
      });
      container.addEventListener("mouseleave", () => {
        isDown = false;
        container.classList.remove("active");
      });
      container.addEventListener("mouseup", () => {
        isDown = false;
        container.classList.remove("active");
      });
      container.addEventListener("mousemove", (e) => {
        if (!isDown) {
          return;
        }
        e.preventDefault();
        const x = e.pageX - container.offsetLeft;
        const walk = (x - startX) * 2; // scroll-fast
        container.scrollLeft = scrollLeft - walk;
      });
      // Mouse wheel for scrolling
      container.addEventListener("wheel", (e) => {
        e.preventDefault();
        container.scrollLeft += e.deltaY;
      });
      // Touch events for mobile
      container.addEventListener("touchstart", (e) => {
        isDown = true;
        startX = e.touches[0].pageX - container.offsetLeft;
        scrollLeft = container.scrollLeft;
      });
      container.addEventListener("touchend", () => {
        isDown = false;
      });
      container.addEventListener("touchmove", (e) => {
        if (!isDown) {
          return;
        }
        const x = e.touches[0].pageX - container.offsetLeft;
        const walk = (x - startX) * 2; // scroll-fast
        container.scrollLeft = scrollLeft - walk;
      });
    }
  };
</script>
<style scoped>
  .ry_scroll-container {
    overflow: hidden;
    white-space: nowrap;
    cursor: grab;
    width: calc(100% - 20px);
    user-select: none; /* Prevent text selection */
  }
  .ry_scroll-container.active {
    cursor: grabbing;
  }
  .ry_scroll-content {
    display: inline-block;
  }
</style>
